package com.team.six.bluecatshop.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.team.six.bluecatshop.domain.Customer;
import com.team.six.bluecatshop.domain.Indent;
import com.team.six.bluecatshop.domain.Product;
import com.team.six.bluecatshop.mapper.TestYingsheProductMapper;
import com.team.six.bluecatshop.mapper.TestYingsheUserMapper;
import com.team.six.bluecatshop.service.*;
import com.team.six.bluecatshop.utils.CodeUtil;
import com.team.six.bluecatshop.utils.Email;
import com.team.six.bluecatshop.utils.SmsTool;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;

@Controller
@RequestMapping("/customerLogin")
public class CustomerLoginController {
    @Autowired
    private ProductService productService;
    @Autowired
    SkuService skuService;
    @Autowired
    ProductTypeService productTypeService;
    @Autowired
    CustomerService customerService;
    @Autowired
    AddressService addressService;
    @Autowired
    IndentService indentService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    TestYingsheUserMapper testYingsheUserMapper;
    @Autowired
    TestYingsheProductMapper testYingsheProductMapper;


    private final int BUFF_SIZE = 4096;//设置hdfs的端口

    //跳转至登录页面
    @GetMapping("/login")
    public String getlogin(HttpSession session) {
        if(session.getAttribute("customerId") != null ){
            session.invalidate();
        }
        return "login";
    }

    //手机号,密码登录
    @PostMapping("/phoneLogin")
    public String postPhoneLogin(String customerPhone, String customerPassword, Model model, HttpSession session) throws IOException {
        Customer c = customerService.findCustomerByPhone(customerPhone);
        if (c == null) {
            System.out.println("error");
            model.addAttribute("msg","unexist");
            return "login";
        }
        if (c.getCustomerPassword().equals(customerPassword)) {
            session.setAttribute("customerId",c.getCustomerId());
            //此处只能放session
            List<Indent> indentsIdentifyZero = indentService.findByCustomerIdAndIdentify0(c.getCustomerId());
            List<Indent> indentsIdentifyOne = indentService.findByCustomerIdAndIdentify1(c.getCustomerId());
            session.setAttribute("indentsIdentifyZero",indentsIdentifyZero);
            session.setAttribute("indentsIdentifyOne",indentsIdentifyOne);
            int count = shoppingCartService.findShoppingCartByCustomerID(c.getCustomerId());
            session.setAttribute("count",count);
            //-----------------将为用户推荐的商品从hdfs中下载下来------------------------------
            System.setProperty("HADOOP_USER_NAME","masterlb");
            FileSystem fs;
            FileContext fileContext;
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS","hdfs://hadoopmaster:9000");
            fs = FileSystem.get(conf);
            fileContext = FileContext.getFileContext(conf);
            try {
                fs.copyToLocalFile(false,new Path("/user/masterlb/output/recommend"+testYingsheUserMapper.findByCustomerId(c.getCustomerId()).getUserid()),new Path("data/"),true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //-----------------------------------------------------------------
            //---------------拿到为用户推荐的商品映射id--------------------
            Reader reader = new FileReader("data/recommend"+testYingsheUserMapper.findByCustomerId(c.getCustomerId()).getUserid());
            // 这里我们用到了字符操作的BufferedReader类
            BufferedReader bufferedReader = new BufferedReader(reader);
            List<Integer> recommendProduct = new ArrayList<>();
            String string = null;
            // 按行读取，结束的判断是是否为null，按字节或者字符读取时结束的标志是-1
            while ((string = bufferedReader.readLine()) != null) {
                String[] split = string.split(",");
                recommendProduct.add(Integer.valueOf(split[1]));
            }
            // 注意这两个关闭的顺序
            bufferedReader.close();
            reader.close();
            List<Product> products=new ArrayList<>();
            for (Integer r: recommendProduct){
                //System.out.println(r);
                //根据映射id找到对应商品并存在list中
                Product product=productService.findById(testYingsheProductMapper.selectByPrimaryKey(r).getProductid());
                product=productService.setImgToProduct(product);
                products.add(product);
            }
            session.setAttribute("recommendProducts",products);//放到session中推荐用
            //-----------------------------------------------------
        } else {
            System.out.println("fail");
            model.addAttribute("msg","error");
            return "login";
        }

        return "redirect:/customer/person_center";
    }
    //手机号,验证码登录
    @PostMapping("/phoneMessageLogin")
    public String postPhoneMessageLogin(String customerPhone, String phoneCode, Model model, HttpServletRequest request) {
        Customer c = customerService.findCustomerByPhone(customerPhone);
        if (c == null) {
            System.out.println("error");
            return "login";
        }else if(!request.getSession().getAttribute("codeMessagePhone").equals(phoneCode)){
            System.out.println("验证码错误");
            return "login";
        } else {
            request.getSession().setAttribute("customerId",c.getCustomerId());
            System.out.println("登录成功");


            return "redirect:/customer/person_center";
        }

    }
    /**
     * 发送登录手机短信
     */
    @PostMapping("/loginMessage")
    @ResponseBody
    public String postPhoneMessage(String phone,HttpSession session) throws ClientException {

        // 验证码（指定长度的随机数）
        String code = CodeUtil.generateVerifyCode(6);
        String TemplateParam = "{\"code\":\""+code+"\"}";
        // 短信模板id
        String TemplateCode = "SMS_170841971";
        SendSmsResponse response = SmsTool.sendSms(phone,TemplateParam,TemplateCode);
        System.out.println(response.getCode());

        session.setAttribute("codeMessagePhone",code);
        if( response.getCode().equals("OK")) {
            return "发送成功";
        }
        return "发送失败";
    }
    //邮件登录
    @PostMapping("/EmailLogin")
    public String postEmailLogin(String customerEmail, String customerPassword, Model model,HttpSession session) {
        Customer c = customerService.findCustomerByEmail(customerEmail);
        if (c == null) {
            System.out.println("error");
            model.addAttribute("msg","unexist");
            return "login";
        }
        if (c.getCustomerPassword().equals(customerPassword)) {
            session.setAttribute("customerId",c.getCustomerId());
            model.addAttribute("customer", c);
        } else {
            System.out.println("fail");
            model.addAttribute("msg","error");
            return "login";
        }

        return "redirect:/customer/person_center";
    }

    //跳转至注册页面
    @GetMapping("/register")
    public String getregister() {
        return "register";
    }

    //手机号注册
    @PostMapping("/phoneRegister")
    public String postPhoneRegister(String customerPhone, String customerPassword,String phoneCode,HttpServletRequest request,Model model) {
        //System.out.println(request.getSession().getAttribute("CodePhone"));
        //System.out.println(phoneCode);
        if (!request.getSession().getAttribute("CodePhone").equals("")){
            if (!request.getSession().getAttribute("CodePhone").equals(phoneCode)){
                System.out.println("验证码错误");
                model.addAttribute("msg","error");
                return "register";
            }else if (customerService.findCustomerByPhone(customerPhone) != null) {
                System.out.println("该用户已经存在");
                model.addAttribute("msg","exist");
                return "register";
            } else {
                Customer customer = new Customer();
                customer.setCustomerPhone(customerPhone);
                customer.setCustomerPassword(customerPassword);
                customerService.add(customer);
                return "login";
            }
        }
        model.addAttribute("msg","error");
        return "register";
    }

    //邮件注册
    @PostMapping("/emailRegister")
    public String postEmailRegister(String customerEmail, String customerPassword,String emailCode,HttpServletRequest request,Model model) {
        //System.out.println(request.getSession().getAttribute("codeEmail"));
        //System.out.println(emailCode);
        if (!request.getSession().getAttribute("codeEmail").equals("")){
            if (!request.getSession().getAttribute("codeEmail").equals(emailCode)){
                System.out.println("验证码错误");
                model.addAttribute("msg","error");
                return "register";
            } else if (customerService.findCustomerByEmail(customerEmail) != null) {
                System.out.println("该用户已经存在");
                model.addAttribute("msg","exist");
                return "register";

            } else {
                Customer customer = new Customer();
                customer.setCustomerEmail(customerEmail);
                customer.setCustomerPassword(customerPassword);
                customerService.add(customer);
                model.addAttribute("msg","success");
                return "login";
            }
        }
        model.addAttribute("msg","error");
        return "register";
    }

    /**
     * 邮件发送
     * @param email
     * @param session
     * @return
     */
    @GetMapping("/email")
    @ResponseBody
    public String email(String email, HttpSession session) {
        Map<String,Object> map = new HashMap<>();
        System.out.print(email);
        UUID uuid = UUID.randomUUID();
        String code = uuid.toString();
        code=code.substring(code.length()-4,code.length());
        System.out.println(code);
        //标题
        String title = "验证码 - BlueCat购物平台";
        //内容
        String text = "<h1>验证你的e-mail</h1>"
                + "<p style='color: grey; font-size: 18px;'>感谢你注册BlueCat购物平台!</p>"
                + "<p style='color: grey; font-size: 18px;'>为了完成帐号设定，请验证你的e-mail地址.</p>"
                + "<span style='color: grey; font-size: 18px;'>你的验证码：</span><span style='font-size: 20px; font-weight: bold;'>" + code + "</span>"
                + "<p style='color: grey; font-size: 15px;'>(10分钟内有效)</p>";

        try {
            Email.send_mail(email, title, text);
            session.setAttribute("codeEmail",code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "发送成功";
    }
    @RequestMapping("/register_test")
    public String registerTest(){

        return "/login";
    }

    /**
     * 发送注册短信
     * @param phone
     * @param session
     * @return
     * @throws ClientException
     */
    @GetMapping("/registerMessage")
    @ResponseBody
    public String smsXxs(String phone, HttpSession session) throws ClientException {
//        Map<String,Object> map = new HashMap<>();
        // 验证码（指定长度的随机数）
        System.out.println(phone);
        String code = CodeUtil.generateVerifyCode(6);
        String TemplateParam = "{\"code\":\""+code+"\"}";
        // 短信模板id
        String TemplateCode = "SMS_170836643";
        SendSmsResponse response = SmsTool.sendSms(phone,TemplateParam,TemplateCode);
        System.out.println(response.getCode());
//        map.put("verifyCode",code);
//        map.put("phone",phone);
        session.setAttribute("CodePhone",code);
        if( response.getCode().equals("OK")) {
            return "发送成功";
//            map.put("isOk","OK");
        }
        return "发送失败";
    }

    /**
     * 发送登录短信
     * @param phone
     * @param request
     * @return
     * @throws ClientException
     */
    @RequestMapping("/loginMessage")
    @ResponseBody
    public Map<String,Object> loginMessage(String phone, HttpServletRequest request) throws ClientException {
        Map<String,Object> map = new HashMap<>();
        // 验证码（指定长度的随机数）
        String code = CodeUtil.generateVerifyCode(6);
        String TemplateParam = "{\"code\":\""+code+"\"}";
        // 短信模板id
        String TemplateCode = "SMS_170841971";
        SendSmsResponse response = SmsTool.sendSms(phone,TemplateParam,TemplateCode);
        System.out.println(response.getCode());
        map.put("code",code);
        map.put("phone",phone);
        request.getSession().setAttribute("code",map);
        if( response.getCode().equals("OK")) {
            map.put("isOk","OK");
        }
        return map;
    }


}
